from helpers import updateInfo
from api import ApiRest
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class API(webapp.RequestHandler):
    """ Handle API calls AJAX class """
    def get(self):
        RestUtilObj=ApiRest.RestUtils()
        data = RestUtilObj.processRequest(self.request)
        if (data.getData()==''):
            self.response=RestUtilObj.sendResponse(400, '', 'text/html', self.response)
        else:
            if data.getMethod()=="get":
                if data.getHttpAccept()=="json":
                    stockHolders = updateInfo.getStockHolders(data.getData().lower())
                    popularityNum, popularityTitle = updateInfo.getPopular(stockHolders)
                    self.response=RestUtilObj.sendResponse(200, simplejson.dumps({'holders': stockHolders, 'popular-title': popularityTitle, 'popular-number': popularityNum}), 'application/json', self.response)
                else:
                    self.response=RestUtilObj.sendResponse(400, '', 'text/html', self.response)
            else:
                self.response=RestUtilObj.sendResponse(405, '', 'text/html', self.response)

    
application = webapp.WSGIApplication(
                                     [('/api', API)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()